package com.zpark.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder() {
        // 使用 BCrypt 强哈希加密
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .cors().and() // 启用CORS支持
            .csrf().disable() // 禁用CSRF保护（API服务通常不需要）
            .authorizeRequests()
            .antMatchers(
                "/views/login",
                "/views/register",
                "/api/public/**",
                "/appointments/**",
                "/api/diagnosis-records/**",
                "/api/first-aid-guides/**",
                "/api/health-reports/**",
                "/api/hospitals/**",
                "/api/medical-records/**",
                "/api/medical-reports/**",
                "/patient/health/**",
                "/api/patients/**",
                "/api/patient-vitals/**",
                "/tcm-diagnosis-records/**",
                "/api/tcm-prescriptions/**",
                "/api/western-medication/**"
            ).permitAll() // 放行公共接口
            .anyRequest().authenticated()
            .and()
            .formLogin().disable() // 禁用表单登录（如果是纯API）
            .httpBasic().disable(); // 禁用HTTP基本认证
    }


    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOriginPattern("*"); // 允许所有来源（生产环境应限制）
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}
